/**
 * Created by Administrator on 2016/3/18.
 */

function delBlock(obj){
    var $obj = $(obj).parent();
    $obj.remove();

    if($('.gridly>.brick').size()==0){
        $('.gridly').append($('#control').show());
    }

}
function showAdd(obj){
    var $obj = $(obj).parent();
    if($obj.next().attr('id')=='control'){
        $('#control').insertAfter($('#controlHold')).hide();
        return;
    }
    $('#control').show().insertAfter($obj);
}
function getEvent(event) {
    switch (event.type) {
        case 'touchstart':
        case 'touchmove':
        case 'touchend':
        case 'touchcancel':
            return event.originalEvent.touches[0];
        default:
            return event;
    }
}

//长按判断
var timeout ;
var isDrag=false;

$(document).ready( function () {
    var text = document.getElementById("t1");
    if(text){
        autoTextarea(text);// 调用
    }


    var idIndex=2;
    function onstart(event,obj){
        event.preventDefault();
        event.stopPropagation();
        var $obj=$(obj);

        selectedDivId = $obj.parent().index();
        timeout = setTimeout(function() {
            dragStart(event,$obj);
        }, 500);
    }

    function dragStart(event,obj){
        event.preventDefault();
        event.stopPropagation();
        event = getEvent(event);
        //拖拽对象
        selectedDiv = $(obj).parent();
        if(selectedDivId!=selectedDiv.index()){
            return ;
        }
        //鼠标元素相对偏移量
        range.y = event.pageY - selectedDiv.offset().top;
        selectedDivId = selectedDiv.index();
        selectedDivHeight = selectedDiv.height();
        selectedDivHalf = selectedDivHeight/2;
        isDrag=true;
        selectedDiv.addClass("maindash");
    }


    var range = {x: 0, y: 0};//鼠标元素偏移量
    var mousePos = {x: 0, y: 0, x1: 0, y1: 0}; //拖拽对象的四个坐标
    var tarPos = {x: 0, y: 0, x1: 0, y1: 0}; //目标元素对象的坐标初始化

    var selectedDiv = null;//拖拽对象 拖拽状态
    var selectedDivId = 0, selectedDivHeight = 0, selectedDivHalf = 0;
    tarFirstY = 0; //拖拽对象的索引、高度、的初始化。
    var tarDiv = null, tarFirst;  //要插入的目标元素的对象, 临时的虚线对象




    $(".dragable>.article_con").each(function () {
        $(this).on('mousedown touchstart', function (event) {
            onstart(event,this);

        });
    });

    $(document).on('mousemove touchmove', function (event) {

        if (!isDrag) return;
        event.preventDefault();
        event.stopPropagation();


        event = getEvent(event);
        //dash 的Y坐标
        mousePos.y = event.pageY - range.y;
        mousePos.y1 = mousePos.y - selectedDivHeight;

        // 拖拽元素随鼠标移动 查找插入目标元素
        var $blocks = $('.dragable').not(".maindash"); // 局部变量：按照重新排列过的顺序  再次获取 各个元素的坐标，
        tempDiv = $(".maindash"); //获得临时 虚线框的对象

        var tarFirst = $blocks.eq(0); // 获得第一个元素
        tarFirstY = tarFirst.offset().top + selectedDivHalf; // 第一个元素对象的中心纵坐标

        //拖拽对象 移动到第一个位置
        if (mousePos.y <= tarFirstY) {
            selectedDiv.insertBefore(tarFirst);
            return;
        }

        $blocks.each(function () {
            tarDiv = $(this);
            tarPos.y = tarDiv.offset().top;
            tarPos.y1 = tarPos.y+ tarDiv.height()/2;
            //判断要插入目标元素的 坐标后， 直接插入
            if (mousePos.y >= tarPos.y1) {
                selectedDiv.insertAfter(tarDiv);
            }

        });

    }).on('mouseup touchend', function (event) {
        clearTimeout(timeout);
        if (isDrag) {
            event.preventDefault();
            event.stopPropagation();
            selectedDiv.removeClass("maindash");
            isDrag = false;
        }else{
            if(event.target.tagName=='TEXTAREA'){
                var $textarea=$(event.target);
                var v=$textarea.val();
                $textarea.val('').focus().val(v);//光标定位到最后
                event.preventDefault();
                event.stopPropagation();
            }
        }
    });
    $('.delete').on('click',function(){delBlock(this);});
    $('.add-icon').on('click',function(){showAdd(this);});
    $('#add-text').on('click',
        function(){
            var $newBrick=$('<div class="brick dragable" ><a class="delete" href="javascript:void(0)" onclick="delBlock(this)"></a><p class="article_con"><textarea id="t'+idIndex+'" name="content[]" placeholder="请输入"></textarea></p><a href="javascript:void(0)" onclick="showAdd(this)" class="add-icon add"></a></div>');
            $newBrick.find('.article_con').on('mousedown touchstart', function (event) {
                onstart(event,this)
            });
            $('#control').before($newBrick);
            var text = document.getElementById("t"+idIndex);
            autoTextarea(text);// 调用
            idIndex++;
        }
    );

    var target = 0;
    $('#imgCancel').click(function(event){$(".hint-box").css({"display": "none"});$('#selectFile,#headPic,#headPic2').val('');});
    $("#imgOk").click(function(event) {
        $(".hint-box").css({"display": "none"});
        $('#selectFile,#headPic,#headPic2').val('');
        if (window.target==1) {
            var dataUrl=cropper.getDataURL();
            uploadBase64IMG(dataUrl,function(url){
                var image = document.getElementById('headPreview');// new Image();
                image.src = url;
                $('#listPic').val(url);
                saveDraft();
            });
        }else if(window.target==2) {

            var htmlstr = '';
            htmlstr += '<div class="picture_box">';
            htmlstr += '<img id="headPreview" >';
            htmlstr += '<input type="hidden" name="listPic" id="listPic" value="">';
            htmlstr += '<a href="javascript:void(0);" class="a-upload">';
            htmlstr += '<input type="file" id="headPic">选取图片';
            htmlstr += '</a>';
            htmlstr += '</div>';
            $("#head").empty().append(htmlstr);
            $('#headPic').on('change',changeFile);
            var dataUrl=cropper.getDataURL();
            uploadBase64IMG(dataUrl,function(url){
                var image = document.getElementById('headPreview');// new Image();
                image.src = url;
                $('#listPic').val(url);
                saveDraft();
            });
        }else{
            var dataUrl=cropper.getDataURL();
            uploadBase64IMG(dataUrl,function(url){
                var $newBrick=$('<div class="brick dragable" ><a class="delete" href="javascript:void(0);" onclick="delBlock(this)"></a><p class="article_con"><img src="" /><input type="hidden" name="content[]"></p><a href="javascript:void(0);" class="add-icon add" onclick="showAdd(this)"></a></div>')
                $newBrick.find('img').attr('src',url);
                $newBrick.find('input:input').val(url);
                $("#control").before($newBrick);

                $newBrick.find('.article_con').on('mousedown touchstart', function (event) {
                    onstart(event,this)
                });
                saveDraft();
            })

        }
    });
    $("#submit").on('click',function(){
        $("#contributeForm").submit();
    });









});
function uploadBase64IMG(imgDataUrl,func){
    $.post('./index.php?m=Api&c=index&a=base64upload',{dataURL:imgDataUrl},
        function(result){
            if(result.status!=0){
                alert("图片上传失败");
            }else{
                func(result.url)
            }
        },'json'
    )
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////

